package com.zzyl.nursing.service.impl;

import java.time.LocalTime;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.nursing.config.WebSocketServer;
import com.zzyl.nursing.domain.AlertData;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.service.IAlertDataService;
import com.zzyl.nursing.vo.AlertNotifyVo;
import com.zzyl.system.mapper.SysUserRoleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.AlertRuleMapper;
import com.zzyl.nursing.domain.AlertRule;
import com.zzyl.nursing.service.IAlertRuleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import javax.script.ScriptEngine;
import javax.script.ScriptException;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;

/**
 * 报警规则Service业务层处理
 *
 * @author syl
 * @date 2025-06-05
 */
@Service
public class AlertRuleServiceImpl extends ServiceImpl<AlertRuleMapper,AlertRule> implements IAlertRuleService
{
    @Autowired
    private AlertRuleMapper alertRuleMapper;

    /**
     * 查询报警规则
     *
     * @param id 报警规则主键
     * @return 报警规则
     */
    @Override
    public AlertRule selectAlertRuleById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询报警规则列表
     *
     * @param alertRule 报警规则
     * @return 报警规则
     */
    @Override
    public List<AlertRule> selectAlertRuleList(AlertRule alertRule)
    {
        return alertRuleMapper.selectAlertRuleList(alertRule);
    }

    /**
     * 新增报警规则
     *
     * @param alertRule 报警规则
     * @return 结果
     */
    @Override
    public int insertAlertRule(AlertRule alertRule)
    {
        return save(alertRule)?1:0;
    }

    /**
     * 修改报警规则
     *
     * @param alertRule 报警规则
     * @return 结果
     */
    @Override
    public int updateAlertRule(AlertRule alertRule)
    {
        return updateById(alertRule)?1:0;
    }

    /**
     * 批量删除报警规则
     *
     * @param ids 需要删除的报警规则主键
     * @return 结果
     */
    @Override
    public int deleteAlertRuleByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids))?1:0;
    }

    /**
     * 删除报警规则信息
     *
     * @param id 报警规则主键
     * @return 结果
     */
    @Override
    public int deleteAlertRuleById(Long id)
    {
        return removeById(id)?1:0;
    }

    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Override
    public void alertFilter() {
        // 查询所有的规则 判断是否有规则
        long count = count(Wrappers.<AlertRule>lambdaQuery().eq(AlertRule::getStatus, 1));
        if (count < 1) {  //没有规则
            return;  //直接结束
        }
        // 从Redis中获取所有设备上报的数据
        List<Object> values = redisTemplate.boundHashOps(CacheConstants.IOT_DEVICE_LAST_DATA).values();
        if (CollUtil.isEmpty(values)) { // Redis中没有数据
            return;
        }
        List<DeviceData> deviceDataList = new ArrayList<>();
        values.forEach(value -> {
            deviceDataList.addAll(JSONUtil.toList(value.toString(), DeviceData.class));
        });


        int i = 1;
        for (DeviceData deviceData : deviceDataList) {
            // 开始一条一条的处理
            System.out.println(i+"-----------"+deviceData);
            alterFilter(deviceData);
            i++;
        }
    }

    // 针对每一条上报的数据做规则的处理
    // {id:25307
    // deviceName:"202-1老吴的睡眠监测带"
    // iotId:"683d592432771f177b3df950_sleep03"
    // productKey:"683d592432771f177b3df950"
    // productName:"睡眠监测带"
    // functionId:"HeartRate"
    // locationType:1
    // physicalLocationType:2
    // deviceDescription:"2,9,12"
    // dataValue:"139"
    // alarmTime:1749010783000}

    private void alterFilter(DeviceData deviceData) {

        // 查询报警规则 查两次

        // 1、只针对这一个设备的  status   iotId   functionId
        List<AlertRule> alertRuleList1 = list(Wrappers.<AlertRule>lambdaQuery()
                        .eq(AlertRule::getStatus, 1)
                        .eq(AlertRule::getIotId, deviceData.getIotId())
                        .eq(AlertRule::getFunctionId, deviceData.getFunctionId())
        );
        // 2、针对所有这个产品下的设备  status    -1   functionId
        List<AlertRule> alertRuleList2 = list(Wrappers.<AlertRule>lambdaQuery()
                .eq(AlertRule::getStatus, 1)
                .eq(AlertRule::getIotId, "-1")
                .eq(AlertRule::getFunctionId, deviceData.getFunctionId())
        );

        // 合并两个规则列表
        Collection<AlertRule> alertRuleList = CollUtil.addAll(alertRuleList1, alertRuleList2);

        // 判断是否有规则
        if(CollUtil.isEmpty(alertRuleList)){
            return;
        }

        for (AlertRule alertRule : alertRuleList) {
            // 准备校验
            deviceDataAlarmHandler(alertRule, deviceData);
        }


    }

    @Autowired
    private ScriptEngine scriptEngine;

    private void deviceDataAlarmHandler(AlertRule alertRule, DeviceData deviceData) {
        System.out.println("开始处理四层的校验的第一层......");
        String period = alertRule.getAlertEffectivePeriod();  //16:00:00~18:59:59
        LocalTime startTime = LocalTime.parse(period.split("~")[0]);
        LocalTime endTime = LocalTime.parse(period.split("~")[1]);
        LocalTime localTime = deviceData.getAlarmTime().toLocalTime();

        //  16:00:00       18:59:59
        if(localTime.isBefore(startTime) || localTime.isAfter(endTime)){
            return;
        }
        System.out.println("开始处理四层的校验的第二层......");

        // 拼凑一个表达式  上报的数据+运算符+阈值
       String expression = deviceData.getDataValue() + alertRule.getOperator() + alertRule.getValue();

       // 计算这个表达式的结果
        boolean  isReach = false;  //上报的数据是否达到阈值
        try {
            isReach = Boolean.parseBoolean(scriptEngine.eval(expression)+"")  ;
        } catch (ScriptException e) {
            e.printStackTrace();
            isReach = false;
        }
        String alertCountKey=  CacheConstants.ALERT_TRIGGER_COUNT_PREFIX+alertRule.getIotId()+ deviceData.getProductKey()+alertRule.getFunctionId();
        String slientKey = CacheConstants.ALERT_SILENT_PREFIX+alertRule.getIotId()+ deviceData.getProductKey()+ alertRule.getFunctionId();

        if(!isReach){
            redisTemplate.delete(alertCountKey); //删除报警数
            return;  // 不需要报警
        }
        System.out.println("开始处理四层的校验的第三层......");

        // 针对这个设备的物模型是否有沉默周期
        if (redisTemplate.hasKey(slientKey)) {
            return;
        }

        System.out.println("开始处理四层的校验的第四层......");

        Long count = redisTemplate.boundValueOps(alertCountKey).increment(1);
        if (alertRule.getDuration()>count) {
            return;
        }

        // 可以报警了
        redisTemplate.delete(alertCountKey); //删除报警数
        //添加沉默周期
        redisTemplate.boundValueOps(slientKey).set("",alertRule.getAlertSilentPeriod(), TimeUnit.MINUTES);


        System.out.println("校验全部通过");

        // 插入报警数据
        insertAlertData(alertRule, deviceData);
    }


    // DeviceData：针对每一条上报的数据做规则的处理
    // {id:25307
    // deviceName:"202-1老吴的睡眠监测带"
    // iotId:"683d592432771f177b3df950_sleep03"
    // productKey:"683d592432771f177b3df950"
    // productName:"睡眠监测带"
    // functionId:"HeartRate"
    // locationType:1
    // physicalLocationType:2
    // deviceDescription:"2,9,12"
    // dataValue:"139"
    // alarmTime:1749010783000}

    @Autowired
    private DeviceMapper deviceMapper;
    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;


    // alert:
    // deviceMaintainerRole
    @Value("${alert.deviceMaintainerRole}")
    private String deviceMaintainerRole;

    @Value("${alert.managerRole}")
    private String managerRole;

    @Autowired
    private IAlertDataService alertDataService;

    private void insertAlertData(AlertRule alertRule, DeviceData deviceData) {
        // 查人
        // locationType '位置类型 0：随身设备 1：固定设备',
        // 判断上报的数据是否为老人的数据
        List<Long> userIds = List.of();
        if (deviceData.getLocationType().equals(0)) {
            // 随身的
            // 根据这个设备找到护理员
            userIds = deviceMapper.selectNursingIdsByIotIdWithElder(deviceData.getIotId());
        }else{
            // 继续判断固定设备是在床位上还是在房间里
            // physicalLocationType：'物理位置类型 0楼层 1房间 2床位',
            if (deviceData.getPhysicalLocationType().equals(1)) {
              userIds = sysUserRoleMapper.selectUserIdByRoleName(deviceMaintainerRole);

            }else if (deviceData.getPhysicalLocationType().equals(2)){
             userIds = deviceMapper.selectNursingIdsByIotIdWithBed(deviceData.getIotId());
            }
        }
        //所有的报警数据都要经过超级管理员
        List<Long> adminIds = sysUserRoleMapper.selectUserIdByRoleName(managerRole);

        // 合并ids
        Collection<Long> userIdList = CollUtil.addAll(userIds, adminIds);
        // 去重
        userIdList = CollUtil.distinct(userIdList);

        List<AlertData> alertDataList = new ArrayList<>();
        for (Long userId : userIdList) {
            AlertData alertData = new AlertData();
            alertData.setIotId(deviceData.getIotId());
            alertData.setDeviceName(deviceData.getDeviceName());
            alertData.setProductKey(deviceData.getProductKey());
            alertData.setProductName(deviceData.getProductName());
            alertData.setFunctionId(deviceData.getFunctionId());
            alertData.setAccessLocation(deviceData.getAccessLocation());
            alertData.setLocationType(deviceData.getLocationType());
            alertData.setPhysicalLocationType(deviceData.getPhysicalLocationType());
            alertData.setDeviceDescription(deviceData.getDeviceDescription());
            alertData.setDataValue(deviceData.getDataValue());
            alertData.setAlertRuleId(alertRule.getId());  //规则的id
            alertData.setAlertReason(deviceData.getFunctionId()+alertRule.getOperator()+alertRule.getValue()+alertRule.getDuration()+alertRule.getAlertSilentPeriod());  //报警原因  报警原因，格式：功能名称+运算符+阈值+持续周期+沉默周期
            // alertData.setProcessingResult("");
            // alertData.setProcessorId(0L);
            // alertData.setProcessorName("");
            // alertData.setProcessingTime(LocalDateTime.now());
            alertData.setType(alertRule.getAlertDataType());  //报警数据类型，0：老人异常数据，1：设备异常数据
            alertData.setStatus(0); //0：待处理，1：已处理
            alertData.setUserId(userId);

            alertDataList.add(alertData);

        }
        alertDataService.saveBatch(alertDataList);


        websocketNotity(alertDataList.get(0),alertRule,userIdList);

        // 发送websocket消息

    }

    @Autowired
    private WebSocketServer webSocketServer;

    /**
     * websocket推送消息
     * @param alertData
     * @param rule
     * @param allUserIds
     */
    private void websocketNotity(AlertData alertData, AlertRule rule, Collection<Long> allUserIds) {

        //属性拷贝
        AlertNotifyVo alertNotifyVo = BeanUtil.toBean(alertData, AlertNotifyVo.class);
        alertNotifyVo.setAccessLocation(alertData.getRemark());
        alertNotifyVo.setFunctionName(rule.getFunctionName());
        alertNotifyVo.setAlertDataType(rule.getAlertDataType());
        alertNotifyVo.setNotifyType(1);
        //向指定的人推送消息
        webSocketServer.sendMessageToConsumer(alertNotifyVo,allUserIds);

    }

}
